// 本组件用于集团运营首页，计划管理的二级页面（三种）
<template>
  <div>
    <!-- 预测流入 -->
    <div v-if="showTopChart" class="bg-color-fffff padding-20 margin-bottom-20">
      <div class="flex align-center justify-between">
        <div class="flex align-center justify-between half-box padding-left-right-40">
          <div>
            <div class="padding-bottom-5">全年预测现金流入</div>
            <div class="font-size-22 font-weight-700">{{ model.incomeCompare.forecastYearAmount | moneyFilterNoUnit }}<span class="font-size-14">万元</span></div>
          </div>
          <div>
            <div class="padding-bottom-5">计划</div>
            <div class="font-size-22 font-weight-700">{{ model.incomeCompare.planAmount | moneyFilterNoUnit }}<span class="font-size-14">万元</span></div>
          </div>
          <div>
            <div class="padding-bottom-5">
              偏差值<span :class="model.incomeCompare.forecastDifferenceAmount > 0 ? 'color-green' : 'color-red'">{{ model.incomeCompare.forecastDifferenceAmount }}</span>
            </div>
            <div>
              偏差率<span :class="model.incomeCompare.forecastDifferenceRate > 0 ? 'color-green' : 'color-red'">{{ model.incomeCompare.forecastDifferenceRate >= 0 ? '↑' : '↓' }}{{ Math.abs(model.incomeCompare.forecastDifferenceRate) | accMul }}%</span>
            </div>
          </div>
        </div>
        <div class="split-line"></div>
        <div class="flex align-center justify-between half-box padding-left-right-40">
          <div>
            <div class="padding-bottom-5">全年预测支出</div>
            <div class="font-size-22 font-weight-700">{{ model.paymentCompare.forecastYearAmount | moneyFilterNoUnit }}<span class="font-size-14">万元</span></div>
          </div>
          <div>
            <div class="padding-bottom-5">计划</div>
            <div class="font-size-22 font-weight-700">{{ model.paymentCompare.planAmount | moneyFilterNoUnit }}<span class="font-size-14">万元</span></div>
          </div>
          <div>
            <div class="padding-bottom-5">
              偏差值<span :class="model.paymentCompare.forecastDifferenceAmount > 0 ? 'color-red' : 'color-green'">{{ model.paymentCompare.forecastDifferenceAmount }}</span>
            </div>
            <div>
              偏差率<span :class="model.paymentCompare.forecastDifferenceRate > 0 ? 'color-red' : 'color-green'">{{ model.paymentCompare.forecastDifferenceRate >= 0 ? '↑' : '↓' }}{{ Math.abs(model.paymentCompare.forecastDifferenceRate) | accMul }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- echarts -->
    <div class="bg-color-fffff padding-left-20 padding-top-20">
      <div class="flex justify-between padding-bottom-10" v-if="isOperate">
        <div class="font-size-18 font-weight-700">{{ title }}</div>
      </div>
      <div class="margin-top-0 bar-box relative-box" :class="hasIncomePay ? 'bar-box-l' : 'bar-box-m'" v-if="chargeItemList.length > 0">
        <!-- <div class="legend-box">
          <div class="font-weight-700">图例</div>
          <div class="legend-item-box" v-for="(item, index) in chargeItemGroupList" v-tooltip="item.chargeItemName" :key="index">
            <template v-if="index <= 1">
              <span class="line-logo-box" :style="{ background: item.executeColor }"><span :style="{ borderColor: item.executeColor }"></span></span>
            </template>
            <template v-else>
              <span class="rect-logo-box" :style="{ background: item.executeColor }"></span>
            </template>
            {{ item.chargeItemName }}
          </div>
        </div> -->
        <!-- <div class="legend-title font-weight-700">图例 </div> -->
        <div class="absolute-box color-666666 y-explain y-top-explain" v-if="pageType == 'budget' && hasIncome">当月现金流入</div>
        <div class="absolute-box color-666666 y-explain y-top-explain" v-if="pageType == 'execute' && hasIncome" style="left: 21px">当月现金流入预测</div>
        <div class="absolute-box color-666666 y-top-unit">(万元)</div>
        <div class="absolute-box color-666666 y-explain" :class="hasIncomePay ? 'y-bottom-explain' : 'y-top-explain'" v-if="pageType == 'budget' && hasPay">当月支出</div>
        <div class="absolute-box color-666666 y-explain" :class="hasIncomePay ? 'y-bottom-explain' : 'y-top-explain'" v-if="pageType == 'execute' && hasPay" style="left: 55px">当月支出预测</div>
        <bar ref="bar" :key="iguid" :banLegendDefaultClick="true" :ch-config="barConfig" @chartClick="showDialogFn" @clickLegend="clickLegend"></bar>
        <div v-if="isOperate || planType == 'execute'" class="mask" :style="[{ width: maskWidth + 'px' }]"></div>
        <div class="absolute-box explain-box" :class="hasIncomePay ? 'explain-box-l' : 'explain-box-m'">
          <div v-if="hasIncome" class="margin-bottom-30">
            <div class="explain-txt font-size-12">其他收入：包括其他经营活动收入、代暂收款、投资和筹资收入、其他非经营活动收入、集团内部调拨收入</div>
          </div>
          <div v-if="hasPay" class="explain-txt font-size-12">其他支出：营销推广费用、保险、财务和行政费用、店面运营管理费、资本性支出、业主费用、其他非经营活动业务支出、集团内部调拨支出</div>
        </div>
      </div>
      <el-empty v-else description="暂无数据"></el-empty>
    </div>

    <!-- 现金缺口 -->
    <div class="diff-num-box flex" v-if="chargeItemList.length > 0 && showCashGap">
      <div class="diff-title">现金缺口</div>
      <div class="diff-item-box flex">
        <div v-for="item in chargeItemList" :class="item.diffNum > 0 ? 'bg-green' : 'bg-red'" class="diff-item" :key="item.month">{{ item.diffNum }}</div>
      </div>
    </div>

    <cash-dialog ref="cashDialog" :selectTime="cashTime" :bizType="bizType" :title="dialogTitle" :showTime="false" :showFirstLevel="false"></cash-dialog>
  </div>
</template>
<script>
  import lodash from 'lodash';
  import cashDialog from './cashDialog';
  import { toFixedTwo, accSubtr } from '@/common/js/utils';
  import { apiCompareTotal } from '@a/about';
  import Bar from '@c/echarts/bar';
  import * as echartsConfig from '@js/echartsConfig';
  import $ from 'jquery';
  import { guid } from '@/common/js/utils';

  export default {
    props: {
      selectTime: {
        type: String,
        default: '',
      },
      title: {
        type: String,
        default: '',
      },
      //折线图类型类型 budget：预算类 execute：执行类
      pageType: {
        type: String,
        default: '',
      },
      //计划页面相关 类型 year:集团年计划  compile:项目年计划编制  execute:项目计划执行
      planType: {
        type: String,
        default: '',
      },
      //是否显示charts上面的数据
      showTopChart: {
        type: Boolean,
        default: false,
      },
      //是否显示现金缺口
      showCashGap: {
        type: Boolean,
        default: false,
      },
      //是否显示收入相关
      hasIncome: {
        type: Boolean,
        default: false,
      },
      //是否显示支出相关
      hasPay: {
        type: Boolean,
        default: false,
      },
      //数据源
      chartsData: {
        type: Object,
        default: () => {
          return {};
        },
      },
      //是否是集团运营页面
      isOperate: {
        type: Boolean,
        default: false,
      },
    },
    watch: {
      chartsData: {
        deep: true,
        handler(res) {
          let newObj = JSON.parse(JSON.stringify(res));
          this.getData(newObj);
        },
      },
    },
    data() {
      return {
        list: [],
        queryMainStore: false,
        bizType: [], //13 收入 24支出
        dialogTitle: '',
        chargeItemList: [],
        chargeItemGroupList: [],
        barConfig: echartsConfig.barConfig,
        cashTime: '',
        maskWidth: 0,
        model: { paymentCompare: {}, incomeCompare: {} },
        iguid: '',
      };
    },
    computed: {
      hasIncomePay() {
        if (this.hasIncome && this.hasPay) {
          return true;
        }
        return false;
      },
    },
    methods: {
      //数据源
      async getData(res) {
        this.iguid = guid();
        this.initChartData();
        this.initMask();
        let lineAmount = 0; //折线图的数量
        let dataList = []; //柱状图集合
        let incomeDataList = []; //收入预算
        let payDataList = []; //支出预算
        //合并收入和支出为一个list
        res.itemList.forEach(item => {
          item.chargeList = [];
          //收入预算
          let incomeCash = this.pageType == 'budget' ? item.planIncomeCash : item.preYearIncomeCash;
          incomeDataList.push(incomeCash);
          //支出预算
          let paymentCash = this.pageType == 'budget' ? item.planPaymentCash : item.preYearPaymentCash;
          if (this.hasIncome && this.hasPay) {
            payDataList.push(accSubtr(0, paymentCash));
          } else {
            payDataList.push(paymentCash);
          }
          //初始化x轴坐标
          this.barConfig.xAxisData.push(item.month + '月');

          if (this.hasIncome && this.hasPay) {
            //支出的数字为了在echarts负半轴显示，强制变为负数
            item.paymentList.forEach(pay => {
              pay.amount = accSubtr(0, pay.amount);
            });
            item.chargeList = item.incomeList.concat(item.paymentList);
          } else {
            if (this.hasIncome) {
              item.chargeList = item.incomeList;
            } else if (this.hasPay) {
              item.chargeList = item.paymentList;
            }
          }

          item.diffNum = toFixedTwo(item.incomeCash - item.paymentCash); //现金缺口，每月的收入-支出
        });

        //收入支出两条折线 两种情况：1集团年计划页，项目年计划编制页 是 【上一年收入执行，上一年支出执行】 2集团运营首页，项目计划执行页 【收入预算，支出预算】
        let lineTxtList = this.pageType == 'budget' ? ['收入预算', '支出预算'] : ['上一年收入执行', '上一年支出执行'];
        let incomeConfig = this.initLineConfig(lineTxtList[0], incomeDataList, '#F79100', 'income');
        let payConfig = this.initLineConfig(lineTxtList[1], payDataList, '#3384FE', 'pay');
        let chargeItemGroupList = [];

        if (this.hasIncome && this.hasPay) {
          lineAmount = 2;
          dataList.push(incomeConfig);
          dataList.push(payConfig);
          chargeItemGroupList = [
            { chargeItemName: lineTxtList[0], executeColor: '#F79100' },
            { chargeItemName: lineTxtList[1], executeColor: '#3384FE' },
          ];
        } else {
          if (this.hasIncome) {
            lineAmount = 1;
            chargeItemGroupList = [{ chargeItemName: lineTxtList[0], executeColor: '#F79100' }];
            dataList.push(incomeConfig);
          } else if (this.hasPay) {
            lineAmount = 1;
            chargeItemGroupList = [{ chargeItemName: lineTxtList[1], executeColor: '#3384FE' }];
            dataList.push(payConfig);
          }
        }

        let showChargeItemNams = [];

        //初始化echarts数据
        res.itemList[0].chargeList.forEach(item => {
          showChargeItemNams.push(item.chargeItemGroupName);

          dataList.push({
            name: item.chargeItemGroupName,
            type: 'bar',
            stack: 'total',
            barWidth: '45%',
            label: {
              show: false,
            },
            emphasis: {
              focus: 'series',
            },
            itemStyle: {
              color: item.color,
            },
            data: [],
          });
        });

        //给echarts初始化数据
        dataList.forEach((item, index) => {
          if (index > lineAmount - 1) {
            res.itemList.forEach((charge, chargeIndex) => {
              item.data.push(charge.chargeList[index - lineAmount].amount); //-lineAmount是把折线图的数量剪掉
            });
          }
          this.barConfig.list.push(item);
        });

        this.chargeItemList = res.itemList;

        res.chargeItemChildList = res.chargeItemChildList.filter(item => {
          return showChargeItemNams.indexOf(item.chargeItemName) > -1;
        });

        this.chargeItemGroupList = chargeItemGroupList.concat(res.chargeItemChildList);

        await this.$nextTick();
        this.$refs.bar.initChart();
      },

      //计划和预测对比
      async getCompareTotal() {
        let projectKey = this.isOperate ? localStorage.getItem('projectKey') : this.$route.query.projectKey || '';
        let res = await apiCompareTotal({
          projectKeys: projectKey ? [projectKey] : null,
          year: Number(this.selectTime.split('-')[0]) || 0,
          month: Number(this.selectTime.split('-')[1]) || 0,
        });
        this.model = res;
      },

      //初始化charts配置
      initChartConfig() {
        this.barConfig.list.splice(0, this.barConfig.list.length);
        this.barConfig.dataZoom = false;
        this.barConfig.left = '170px';
        this.barConfig.gridTop = '90px';
        this.barConfig.gridBottom = '30px';
        this.barConfig.legend.show = true;
        this.barConfig.legend.top = 0;
        this.barConfig.legend.right = 0;
        this.barConfig.legend.width = 1250;
        this.barConfig.legend.orient = 'horizontal';
        this.barConfig.xPosition = 'top';
        this.barConfig.yAxis.grainUnit = '';
        this.barConfig.yAxis.gridShow = false;
        this.barConfig.yAxis.splitLineShow = false;

        this.barConfig.tooltip.formatter = function (params) {
          // console.log(params, 'params')
          var res = params[0].name;
          for (var i = 0, l = params.length; i < l; i++) {
            res += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + Math.abs(params[i].value);
          }
          return res;
        };
      },

      //初始化charts数据
      initChartData() {
        this.barConfig.xAxisData.splice(0, this.barConfig.xAxisData.length);
        this.barConfig.list.splice(0, this.barConfig.list.length);
      },

      //点击显示的弹窗
      async showDialogFn(data) {
        console.log(data);
        let month = data.dataIndex + 1;
        let currentMonth = Number(this.selectTime.split('-')[1]) || 0;
        let typeTxt = month > currentMonth ? '预测' : '执行';
        this.dialogTitle = '现金流' + month + '月';
        this.bizType = [1, 2, 3, 4];
        // this.bizType = data.data > 0 ? [1] : [2];
        this.cashTime = '2022-' + month;
        await this.$nextTick();

        if (this.isOperate) {
          this.$refs.cashDialog.init();
        } else {
          this.hasIncomePay && this.toPath(data.data)
        }
      },

      //跳转路径
      toPath(num){
        //planType year:集团年计划  compile:项目年计划编制  execute:项目计划执行
        let pathName = '';
        if (this.planType == 'year') {
          pathName = num > 0 ? '/businessPlan/businessManage/yearIncome' : '/businessPlan/businessManage/yearPay';
        } else if (this.planType == 'compile') {
          pathName = num > 0 ? '/businessPlan/businessManage/compileIncome' : '/businessPlan/businessManage/compilePay';
        } else if (this.planType == 'execute') {
          pathName = num > 0 ? '/businessPlan/businessManage/executeIncome' : '/businessPlan/businessManage/executePay';
        }
        window.location.href = pathName + location.search
      },

      //mask的宽度和位置
      async initMask() {
        await this.$nextTick();
        setTimeout(() => {
          let month = new Date(this.selectTime).getMonth() + 1;
          let baseWidth = document.body.clientWidth - 215;
          //mask的宽度和位置
          let width = 0;
          let index = -1;
          $('.monthRateBox th').each(function () {
            index++;
            if (index > month && index <= 12) {
              // console.log($(this).outerWidth())
              width += $(this).outerWidth();
            }
          });

          this.maskWidth = width;
        }, 300);
      },

      //折线图init数据
      initLineConfig(title, list, color, type) {
        let row = {
          type: 'line',
          name: title,
          color: color,
          data: list,
          label: {
            show: true,
            color: '#333',
            position: type == 'income' ? 'top' : 'bottom',
            formatter: params => {
              let val = '';
              if (type == 'income') {
                val = params.value == 0 ? '' : params.value;
              } else {
                let amount = this.hasIncome && this.hasPay ? accSubtr(0, params.value) : params.value;
                val = params.value == 0 ? '' : amount;
              }
              return val;
            },
          },
        };
        return row;
      },

      //点击bar的legend到字典
      clickLegend(name) {
        let url = '/businessAssets/dataDic/index?token=1BECA34141E04A338B570F70C780C955&menuId=caa9147d6ba64e1a95bd3eeb76cc5203&parentMenuId=7ee2400d0e72437aa3bdb5823497537f&timestamp=1667202507216&keyWord=' + name;
        window.open(url);
      },
    },

    mounted() {
      this.initChartConfig();
      this.getCompareTotal();
    },

    components: { Bar, cashDialog },
  };
</script>

<style lang="scss" scoped>
  .diff-num-box {
    overflow: hidden;
    height: 44px;
    line-height: 44px;
    .diff-title {
      width: 189px;
      text-align: center;
      padding-right: 56px;
    }
    .diff-item-box {
      width: calc(100% - 179px);
      .diff-item {
        width: 8.33%;
        text-align: center;
        margin-left: 1px;
        border-radius: 5px;
      }
      .bg-red {
        background: #ffe5e5;
      }
      .bg-green {
        background: #e9f9f2;
      }
    }
  }
  .bar-box {
    width: 100%;
  }
  .bar-box-l {
    height: 520px;
  }
  .bar-box-m {
    height: 260px;
  }
  .legend-title {
    position: absolute;
    top: 2px;
    right: 1000px;
  }
  .y-explain {
    // writing-mode: tb-rl;
    letter-spacing: 5px;
  }
  .y-top-explain {
    top: 86px;
    left: 53px;
  }
  .y-top-unit {
    top: 37px;
    left: 171px;
  }
  .y-bottom-explain {
    bottom: 29px;
    left: 94px;
  }
  .explain-box {
    width: 160px;
    left: 0;
    .explain-txt {
      line-height: 25px;
    }
  }
  .explain-box-l {
    top: 133px;
  }
  .explain-box-m {
    top: 110px;
  }
  .mask {
    height: 490px;
    background: rgba($color: #dbfeff, $alpha: 1);
    position: absolute;
    top: 30px;
    right: 0;
  }
  .current-month {
    height: 390px;
    width: 1px;
    border-left: 1px dashed #ccc;
    position: absolute;
    top: 0;
  }
  .half-box {
    width: 50%;
  }
  .split-line {
    width: 1px;
    background: #e5e5e5;
    height: 45px;
    margin: 0 20px 0;
  }

  .legend-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: end;
    padding: 0 5px;

    .legend-item-box {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 20px;
      font-size: 12px;
      cursor: pointer;

      .line-logo-box {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 1px;
        width: 30px;
        margin-right: 5px;

        span {
          display: inline-block;
          width: 12px;
          height: 12px;
          border-radius: 6px;
          background: #fff;
          border: 1px solid #fff;
        }
      }

      .rect-logo-box {
        display: inline-block;
        width: 30px;
        height: 15px;
        border-radius: 3px;
        margin-right: 5px;
      }
    }
  }
</style>
